package org.yong.springbootcmd.util;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class BytesUtil {

  /**
   * 整数值转字节数组
   *
   * @param in 输入
   * @param length 字节数组长度, 从低位算起
   * @param useLittleEndian true-LittleEndian, false-Big Endian
   * @return 字节数组
   */
  public static byte[] toBytes(long in, int length, boolean useLittleEndian) {
    if (8 < length || 1 > length) throw new IllegalArgumentException("参数length有效范围: 1 ~ 8");

    ByteBuffer byteBuffer = ByteBuffer.allocate(8);
    byteBuffer.order(useLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
    byteBuffer.asLongBuffer().put(in);
    byte[] array = byteBuffer.array();

    byte[] dist = new byte[length];
    // little endian: 0 ~ len
    // big endian: (maxLen - len) ~ len
    int srcPos = useLittleEndian ? 0 : (array.length - length);
    System.arraycopy(array, srcPos, dist, 0, length);
    return dist;
  }
}
